package com.demo.cms.action.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.apache.struts2.json.annotations.JSON;
import org.apache.struts2.util.ServletContextAware;

import com.demo.Constants;
import com.demo.cms.model.Crop;
import com.demo.common.ImageUtils;
import com.demo.webapp.action.BaseActionSupport;

/**
 * 切割图片Action
 * 对图片进行切割
 * 其中x:x坐标,y:坐标,w:宽度,h:高度,rw:缩略宽度,rh:缩略高度
 * 当w与rw不同时,切割后进行缩略(或放大)设置
 * @author ryuu.kk
 *
 */
public class CropAction extends BaseActionSupport implements ServletContextAware {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -1726780846092685039L;
	
	private ServletContext context;
	/**
	 * 图片切割模型
	 */
	private Crop crop;
	
	/**
	 * 切割方法
	 */
	public String execute() {
		// 得到原始图片地址
		String dir = crop.getDir();
		//ServletContext context = request.getSession(true).getServletContext();
		String realPath = context.getRealPath(dir);
		
		InputStream input = context.getResourceAsStream(realPath);
		try {
			input = new FileInputStream(realPath);
		} catch (FileNotFoundException e) {
			return INPUT;
		}
		BufferedImage image = ImageUtils.cropImage(input, crop.getX(), crop.getY(), crop.getW(), crop.getH());
		
		image = ImageUtils.imageZoom(image, crop.getRw(), crop.getRh());
		String thumbPath = com.demo.webapp.config.Constants.PUBLISH_FOLDER_NAME;
		
		Date now = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		
		String name = now.getTime() + dir.substring(dir.lastIndexOf("."));
		String pathPix = df.format(now);
		// 计算剪切后图片位置：公共路径/基础路径/yyyy/mm/dd/filename(timestamp).ext
		Object baseObj = getConfiguration().get(com.demo.webapp.config.Constants.PUBLISH_FOLDER_KEY);
		if (baseObj != null) {
			thumbPath = baseObj.toString() + "/" + thumbPath;
		}
		thumbPath += "/" + pathPix + "/" + name;
		
		File file = new File(context.getRealPath(thumbPath));
		if (!file.exists()) {
			file.mkdirs();
		}
		
		try {
			ImageIO.write(image, ImageUtils.JPG, file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		crop.setOut(thumbPath);
		crop.setStatus(SUCCESS);
		
		return SUCCESS;
	}

	/**
	 * 图片剪切的行为
	 * 
	 * @return String
	 */
	public String img() {
		
		return execute();
	}
	
	
	@JSON(name="crop")
	public Crop getCrop() {
		return crop;
	}

	public void setCrop(Crop crop) {
		this.crop = crop;
	}

	@Override
	public void setServletContext(ServletContext context) {
		this.context = context;
	}
}
